﻿Imports VMWorkshop.Domain

Partial Public Class WebForms
    Inherits System.Web.UI.Page

    Protected _vm As WebFormsViewModel

    Protected Sub Page_Init(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Init
        Me._vm = New WebFormsViewModel(New ProductRepository())
    End Sub

    Protected Sub grdProducts_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
        Dim productId As String = Me.grdProducts.DataKeys(Me.grdProducts.SelectedIndex)(0).ToString()
        Me._vm.GetSelectedProduct(productId)
    End Sub

    Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As EventArgs)
        Me.Page.Validate()

        If Me.Page.IsValid Then
            Dim view As New ProductEditView()
            view.Description = Me.description.Text
            view.Price = Me.price.Text
            view.ProductId = Me.productId.Value
            view.QuantityOnHand = Me.quantityOnHand.Text
            view.ReleaseDate = Me.releaseDate.Text
            view.Title = Me.title.Text
            Me._vm.PersistChanges(view)
        End If
    End Sub

    ' The reason for using the PreRender event handler is to give the
    ' control event handlers (see above) a chance to fire in the Page
    ' event life cycle before the page finalizes binding data to controls
    ' and setting visibility to items.
    Protected Sub Page_PreRender(ByVal sender As Object, ByVal e As EventArgs) Handles Me.PreRender
        If Not Me.Page.IsPostBack Then
            Me.grdProducts.DataSource = Me._vm.Products
            Me.grdProducts.DataBind()
        End If

        Me.plcEditor.Visible = Me._vm.HasSelectedProduct
        Me.plcSaveComplete.Visible = Me._vm.IsPersistenceSuccessful

        Me.title.Text = Me._vm.SelectedProduct.Title
        Me.description.Text = Me._vm.SelectedProduct.Description
        Me.quantityOnHand.Text = Me._vm.SelectedProduct.QuantityOnHand
        Me.releaseDate.Text = Me._vm.SelectedProduct.ReleaseDate
        Me.price.Text = Me._vm.SelectedProduct.Price
        Me.productId.Value = Me._vm.SelectedProduct.ProductId
    End Sub

End Class